function loadJS(url,callback){var script=document.createElement('script'),fn=callback||function(){};script.type='text/javascript';if(script.readyState){script.onreadystatechange=function(){if(script.readyState=='loaded'||script.readyState=='complete'){script.onreadystatechange=null;fn()}}}else{script.onload=function(){fn()}}script.src=url;document.getElementsByTagName('head')[0].appendChild(script)}

var fnSendData2Qt,
	receiverData,
	loadResource,
	ReceiveMapData;
loadJS('qrc:///weblib/qwebchannel.js', function(){
	// 调用 Qt 对象的方法并传递数据
	new QWebChannel2(qt.webChannelTransport, function (channel) {
		receiverData = channel.objects.receiverData;
		loadResource = channel.objects.loadResource;
		// 监听信号From Qt
		loadResource.resourceLoaded.connect(function(content) {
			if(ReceiveMapData.level == 1)
				fnMapProvChart(content);
			if(ReceiveMapData.level == 2)
				fnMapCityChart(content);
		});
		fnSendData2Qt = function(dataString){
			if(receiverData)
				receiverData.fnReceiveData(dataString);
			else console.error("receiverData is not initialized.");
		}
	});
});

var bgColor=[
    'rgba(32,85,137,1)',
    'rgba(20,137,169,1)',
    'rgba(78,161,56,1)',
    'rgba(166,179,44,1)',
    'rgba(189,93,33,1)',
    'rgba(210,45,22,1)'
];

var mapChart = echarts.init(document.getElementById("myStationMap"), null, {
		renderer: 'canvas'	//默认是 'canvas'，显式声明避免歧义
	});

/** ****************
 * 中国地图_开始
 */	
var ChinaMapData = [
    {name: '北京',value: 0 },{name: '天津',value: 0 },  
    {name: '上海',value: 0 },{name: '重庆',value: 0 },  
    {name: '河北',value: 0 },{name: '河南',value: 0 },  
    {name: '云南',value: 0 },{name: '辽宁',value: 0 },  
    {name: '黑龙江',value: 0 },{name: '湖南',value: 0 },
    {name: '安徽',value: 0 },{name: '山东',value: 0 },  
    {name: '新疆',value: 0 },{name: '江苏',value: 0 },  
    {name: '浙江',value: 0 },{name: '江西',value: 0 },  
    {name: '湖北',value: 0 },{name: '广西',value: 0 },  
    {name: '甘肃',value: 0 },{name: '山西',value: 0 },  
    {name: '内蒙古',value: 0 },{name: '陕西',value: 0 },
    {name: '吉林',value: 0 },{name: '福建',value: 0 },  
    {name: '贵州',value: 0 },{name: '广东',value: 0 },  
    {name: '青海',value: 0 },{name: '西藏',value: 0 },  
    {name: '四川',value: 0 },{name: '宁夏',value: 0 },  
    {name: '海南',value: 0 },{name: '台湾',value: 0 },  
    {name: '香港',value: 0 },{name: '澳门',value: 0 },
    {name: '南海诸岛',value: 0 }
];
var ChinaMapOption = {
    layoutCenter: ['50%', '50%'],
    layoutSize: "120%",
	animation:false,
    tooltip: {
        show:true,
        trigger: 'item',
        formatter: '{b}<br/>{c} 台',
        extraCssText: "background-color:rgba(0,0,0,.7); border:none; color:#FFF;"
    },
    visualMap: {
        type: 'piecewise',
        textStyle: {
            color: '#FFF'
        },
        itemWidth: 30,
        left: 6,
        bottom: 6,
        pieces: [
            {lt: 1, label: '0', color: bgColor[0]},
            {gt: 0, lte: 30, label: '1~30', color: bgColor[1]},
            {gt: 30, lte: 60, label: '31~60', color: bgColor[2]},
            {gt: 60, lte: 90, label: '61~90', color: bgColor[3]},
            {gt: 90, lte: 120, label: '91~120', color: bgColor[4]},
            {gt: 120, label: '120+', color: bgColor[5]}
        ],
        inRange: {
            color: [bgColor[0], bgColor[5]]
        },
        selectedMode: false
    },
    series: [
        {
            name: '中国',
            type: 'map',
            mapType: 'china',
            //selectedMode: 'multiple',
            //width: '86%',
            height: '100%',
            left: '0%',
            label: {
                show: true,
                textStyle: {
                    color: '#FFF',
                    fontSize: 13
                }
            },
            itemStyle: {
                normal: {
                    borderWidth: 0.3,
                    borderColor:'#082858',
                },
                emphasis: {
                    show: true,
                    areaColor: 'rgba(255,255,255,.7)',
                    label: {
                        show: true,
                        textStyle: {
                            color: '#000'
                        }
                    }
                }                     
            },
            roam: false,
            zoom:1,
            selectedMode: false,
            data: ChinaMapData
        }
    ]
};

function fnMapChinaConvCertData(data) {
    if(data === ""){
		return;
	}
	var res = [],
		provName = '',
		bita = ['黑龙江','内蒙古','南海诸岛'];
	for (var i = 0; i < data.length; i++) {
		provName = data[i].provName;
		if(provName){
			provName = data[i].provName.substr(0,2);
			for(j in bita){
                if(provName === bita[j].substr(0,2)){
					provName = bita[j];
					break;
				}
			}                  
			res.push({
				name: provName,
				value: data[i].dCount,
			});
		}
	}
	return res;
}

var fnMapChinaChart= function(){
	let mapData = fnMapChinaConvCertData(ReceiveMapData.data);
	if(Array.isArray(mapData)){
		for (var i in ChinaMapData) {
			for (var j in mapData) {
                if(mapData[j].name === ChinaMapData[i].name){
					ChinaMapData[i].value = mapData[j].value;
					continue;
				}
			}
		}
		ChinaMapOption.series[0].data = ChinaMapData;
	}			
	mapChart.clear();
	try {
		ChinaMapOption && mapChart.setOption(ChinaMapOption);
		let message = {'option':'MapLoadFinished'};
		fnSendData2Qt(JSON.stringify(message));
		//省市 点击事件
		mapChart.off('click').on('click',function(data){
			let proJson = pinyin.getFullChars(data.name).toLowerCase();
			if(data.name === '陕西'){
				proJson = proJson+'1';
			}
			if(data.name === '西藏'){
				proJson = 'xizang';
			}
			if(data.name === '重庆'){
				proJson = 'chongqing';
			}
			if(data.name === '内蒙古'){
				proJson = 'neimenggu';
			}                
			if(data.name === '台湾' || data.name === '南海诸岛'){
				parent.layer.msg(data.name+'暂无业务');
				return;
			}
			
			/*
			* 传值到Qt
			*/
			let message = {'option':'currProvinceChanged','proName':data.name, 'proJson':proJson};
			fnSendData2Qt(JSON.stringify(message));
		})
	}catch(err){
		console.log(err);
		return;
	}
}
/**
 * 中国地图_结束
 * ******************/
 
/**
  * 省市地图_开始
  */
var ProvMapOption = {
    layoutCenter: ['53%', '52.3%'],
    layoutSize: "93%",
    series: [{
        type: 'map',
        mapType: '',
        zoom: 1,
        roam: true,
        label: {
            normal: {
                show: true,
                textStyle: {
                    color: '#FFF',
                    fontSize: 12
                }
            },
            emphasis: {
                show: true,
                textStyle: {
                    color: '#000',
                    fontSize: 14
                }
            }
        },
        itemStyle: {
            normal: {
                borderColor: "#CCC",
                borderWidth: 0.5
            },
            emphasis: {
                show: false,
                areaColor: "rgba(255,255,255,.7)"
            }
        },
        data: [],
        selectedMode: false
    }],
    tooltip : {
        trigger: 'item',
        formatter: '{b}<br>{c} 座',
        itemSize:'14px',
        extraCssText: "background-color:rgba(0,0,0,.7); border:none; color:#FFF;",
    },
    visualMap: {
        type: 'piecewise',
        textStyle: {
            color: '#FFF'
        },
        itemWidth: 30,
        left: 6,
        bottom: 6,
        pieces: [
            {lt: 1, label: '0', color: bgColor[0]},
            {gt: 0, lte: 20, label: '1~20', color: bgColor[1]},
            {gt: 20, lte: 40, label: '21~40', color: bgColor[2]},
            {gt: 40, lte: 60, label: '41~60', color: bgColor[3]},
            {gt: 60, lte: 80, label: '61~80', color: bgColor[4]},
            {gt: 80, label: '80+', color: bgColor[5]}
        ],
        inRange: {
            color: [bgColor[0], bgColor[5]]
        },
        selectedMode: false
    }
};
var fnMapProvChart = function(jsonData = ""){
	if(jsonData === ""){
		// 等待loadResource.resourceLoaded调用成功信号
		loadResource.fnLoadResource(':/weblib/json/'+ReceiveMapData.proJsonName+'.json');
		return false;
	}
	if (!jsonData) {
		console.error('Failed to load JSON file.');
		return;	    
	}
	try {
		let ProvMapData = [],
			jsonResult = JSON.parse(jsonData);
		jsonResult.features.forEach(function(el, i, arr) {
			let cityCode = el.id;
			ProvMapData.push({
				name: el.properties.name,
				//value: randomData(),
				value: 0,
				id: cityCode
			})
		});
		for (var i = 0; i < ProvMapData.length; i++) {
			for(j in ReceiveMapData.data){
				if(ProvMapData[i].id == ReceiveMapData.data[j].cityCode){
					ProvMapData[i].value = ReceiveMapData.data[j].dCount;
					break;
				}
			}
		}
		
		echarts.registerMap(ReceiveMapData.proName, jsonResult);
		ProvMapOption.series[0].mapType = ReceiveMapData.proName;
		ProvMapOption.series[0].data = ProvMapData;
		ProvMapOption.visualMap.bottom = 6;
		
		let mTop10 = ['广东','贵州','福建','重庆','湖北','浙江'];
		if(mTop10.indexOf(ReceiveMapData.proName) !== -1){
			ProvMapOption.visualMap.bottom = 400;
		}
		
		if(ReceiveMapData.proJsonName == "guangdong"){
			ProvMapOption.layoutCenter = ['57%', '40%'];
		}
		
		mapChart.clear();
		try {
			ProvMapOption && mapChart.setOption(ProvMapOption);
			let message = {'option':'MapLoadFinished'};
			fnSendData2Qt(JSON.stringify(message));
			// 区县点击事件
			mapChart.off('click').on('click',function(result){
				let message = {'option':'currCityChanged','cityName':result.data.name,'cityCode':result.data.id};
				fnSendData2Qt(JSON.stringify(message));
				return false;
			});
		}catch(err){
			console.log(err);
			return;
		}
	} catch (error) {
		console.error('Failed to parse JSON:', error);
	}
}
/**
 * 省市地图_结束
 * ******************/
 
/**
 * 区县地图_开始
 */
var CityMapOption = {
    tooltip: {
        show: false
    },
    visualMap:{
        type: 'piecewise',
        textStyle: {
            color: '#FFF'
        },
        right: 6,
        top: 10,
        pieces: [
            {min: 1, max: 1, label: '正常', color: 'rgba(0,131,33,.9)'},
            {min: 2, max: 2, label: '待机', color: 'rgba(0,170,255,.9)'},
            {min: 3, max: 3, label: '报警', color: 'rgba(255,124,0,.9)'},
            {min: 4, max: 4, label: '故障', color: 'rgba(255,25,0,.9)'},
            {min: 5, max: 5, label: '离线', color: 'rgba(144,144,144,.9)'}
        ],
        selectedMode: 'multiple',
        inverse:true,
    },
    geo: [{
        map: '',
        type: 'map',
        layoutCenter: ['43%', '50%'],
        layoutSize: "99%",
        roam: true,
        zoom: 1,
        itemStyle: {
            normal: {
                areaColor: 'rgb(32,64,110)',
                borderColor: '#FFF'
            },
            emphasis: {
                areaColor: '#2C4B79'
            }
        },
        label: {
            normal: {
                show: true,
                textStyle: {
                    color: '#CCC',
                    fontSize: 12
                }
            },
            emphasis: {
                show: true,
                textStyle: {
                    color: '#FFF',
                    fontSize: 13
                }
            }
        }
    }],	
    series: [{
        roam: true,
        type: "effectScatter",
        rippleEffect:{
            scale:3
        },
        coordinateSystem: "geo",
        itemStyle: {
            normal: { color: '#FDFF00' }
        },
        tooltip: {
            show: true,
            trigger: 'item',
            formatter: function (params) {
                return params.name;
            }
        },
        data: [],
    }]
};
var visibilityState = 'hidden',
	mapZoom = 0;
var fnMapCityChart = function(jsonData = ""){
	if(jsonData === ""){
		// 等待loadResource.resourceLoaded调用成功信号
		loadResource.fnLoadResource(':/weblib/json/'+ReceiveMapData.cityCode+'.json');
		return false;
	}
	if (!jsonData) {
		console.error('Failed to load JSON file.');
		return;	    
	}
	try {
		let CityMapData = [],
			jsonResult = JSON.parse(jsonData)
			data = ReceiveMapData.data;
		if(data != null && data.length > 0){
			for(i = 0; i < data.length; i++){
				CityMapData.push({
					name: data[i].stationName +' '+ data[i].deviceName,
					value: [data[i].jingdu, data[i].weidu, data[i].state],
					distCode: data[i].distCode,
					deviceNumber: data[i].deviceNumber,
					infoid: data[i].id
				})
			}
		}
		echarts.registerMap(ReceiveMapData.cityName, jsonResult);
		CityMapOption.series[0].data = CityMapData;
		CityMapOption.geo[0].map = ReceiveMapData.cityName;
		mapChart.clear();
		try {
			CityMapOption && mapChart.setOption(CityMapOption);
			let message = {'option':'MapLoadFinished'};
			fnSendData2Qt(JSON.stringify(message));
			// 设备散点点击事件
			mapChart.off('click').on('click', function (params) {
				//console.log(params.data);
				if (params.componentSubType === 'effectScatter') {
					let message = {
						'option': 'openDeviceDetail',
						'devNumber': params.data.deviceNumber,
						'infoid': params.data.infoid};
					fnSendData2Qt(JSON.stringify(message));
				}
			}).on('georoam',function(params){
				if(params.dy || params.dx){
					return;
				}
				mapZoom = mapChart.getOption().geo[0].zoom;
			});
		}catch(err){
			console.log(err);
			return;
		}
	} catch (error) {
		console.error('Failed to parse JSON:', error);
	}
}
/**
 * 区县地图_结束
 * ******************/

window.addEventListener("resize", function() {
	if(mapChart != null)
		mapChart.resize();
});
 
var fnJudgement = function(){
	let funOk = 0;
    if(ReceiveMapData.level === 1){
		if (typeof fnMapProvChart === 'function' && fnMapProvChart instanceof Function)
			funOk = 1;
	}else if(ReceiveMapData.level === 2){
		if (typeof fnMapCityChart === 'function' && fnMapCityChart instanceof Function)
			funOk = 1;
	}else{
		if (typeof fnMapChinaChart === 'function' && fnMapChinaChart instanceof Function)
			funOk = 1;
	}
	if (funOk == 1)
		ReceiveMapData.level == 1 ? fnMapProvChart() 
			: ReceiveMapData.level == 2 ? fnMapCityChart()
			: fnMapChinaChart();
	else{
		setTimeout(function(){
			fnJudgement();
		}, 1000);
	}
}
 /**
  * 接受外部传值
  */
function fnReceiveMapData(data){
	ReceiveMapData = JSON.parse(data);
	if (typeof ReceiveMapData === 'object' && ReceiveMapData!== null){
		if(Array.isArray(ReceiveMapData.data))
			fnJudgement();
		else console.error('Map data error！', Array.isArray(ReceiveMapData.data));
	}
}

/**
 * 通知qt，JS已经加载完成
 */
function fnJavascriptReady(){
	if ((typeof fnSendData2Qt === 'function' && fnSendData2Qt instanceof Function)
		&& (typeof fnReceiveMapData === 'function' && fnReceiveMapData instanceof Function)){
		let message = {'option':'JavascriptReady'};
		fnSendData2Qt(JSON.stringify(message));
	}else{
		setTimeout(function(){
			fnJavascriptReady();
		}, 800);
	}
}
fnJavascriptReady();
